package com.yunjinsuke.recharge.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 直接使用Redis进行分布式锁
 **/

@Component
@Slf4j
public class RedisLockCommon {

    private final StringRedisTemplate stringRedisTemplate;

    public RedisLockCommon(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     *  * Redis加锁的操作
     *  *
     *  * @param key
     *  * @param value
     *  * @return
     *  
     */
    public Boolean tryLock(String key) {
        String value = String.valueOf(System.currentTimeMillis());
        return stringRedisTemplate.opsForValue().setIfAbsent(key, value);
    }


    /**
     *  * Redis解锁的操作
     *  *
     *  * @param key
     *  * @param value
     *  
     */
    public void unlock(String key) {
        stringRedisTemplate.opsForValue().getOperations().delete(key);
    }
}